Skip to content

feat(vm): interrupt running Lua at a host-set deadline with Lua.set_deadline/2 - #435

Open
dbernheisel wants to merge 7 commits into
deviceio:feat/vm-gcfrom
dbernheisel:feat/vm-deadline
Open

dbernheisel wants to merge 7 commits into
deviceio:feat/vm-gcfrom
dbernheisel:feat/vm-deadline

Conversation

@dbernheisel

@dbernheisel dbernheisel commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

A host that calls back into Lua from an Elixir function can't stop just that callback when it runs long. :max_instructions is per evaluation, and killing the process throws away the whole state. Lua.set_deadline/2 gives running Lua a System.monotonic_time(:millisecond) deadline. Past it, Lua raises a catchable "deadline exceeded" at the next loop back-edge or call, the same places :max_instructions is checked. It's what a lua_sethook count hook gives a host in reference Lua.

  • the clock is read every 256 ticks, and only while a deadline is set
  • a pcall that traps the error is interrupted again on its next tick, so the error reaches the host
  • Lua.deadline/1 returns the current deadline, so a host can give a nested call a shorter one and restore it after
Benchmarks

feat/vm-gc (f5d18a5) vs this branch (105bb9c), lua (chunk) median, quick mode. Base and branch ran interleaved per workload, two rounds averaged (oop five rounds). Apple M4 Max, OTP 29, Elixir 1.20.0. Other work was running on the machine (load 5–11), so a few percent either way is noise.

Workload Base Branch Change
fibonacci 456.3 ms 456.6 ms +0.1%
closures 411.7 μs 411.8 μs +0.0%
oop 114.2 μs 116.5 μs +2.0%
metamethods: self-call method dispatch 511.9 μs 495.4 μs -3.2%
metamethods: 3-level __index chain 208.8 μs 216.3 μs +3.6%
metamethods: arithmetic/relational 2.26 ms 2.15 ms -4.9%
pcall success path 247.6 μs 238.9 μs -3.5%
pcall raise + catch 823.4 μs 802.5 μs -2.5%
varargs + multiple returns 3.58 ms 3.45 ms -3.6%
table.concat 35.9 μs 34.2 μs -4.6%
string.format 85.8 μs 83.4 μs -2.8%
table build 17.8 μs 17.2 μs -3.5%
table sort 23.3 μs 23.1 μs -0.7%
table iterate/sum 24.9 μs 25.2 μs +1.0%
table map + reduce 49.9 μs 50.0 μs +0.3%
table pairs (hash) 85.5 μs 83.6 μs -2.2%

Cost when a deadline is set, on this branch: 4M loop iterations in a compiled function, nine runs each.

Limit Min Median
none 245 ms 251 ms
deadline set, not reached 259 ms 266 ms
max_instructions: 1_000_000_000 338 ms 345 ms

@dbernheisel dbernheisel changed the title feat(vm): interrupt running Lua at a host. Add Lua.set_deadline feat(vm): interrupt running Lua at a host-set deadline with Lua.set_deadline/2 Nov 5, 2026
… limits

Lua.deadline/1 can return :passed, so the save-and-restore pattern raised a
FunctionClauseError after a pcall had trapped the deadline. Accept it, and
correct the docs: the check is a soft limit that does not interrupt stdlib
callbacks or pattern matching, a passed deadline stays on the returned state,
and a pcall followed by return completes normally.
Comment thread lib/lua/vm/dispatcher.ex Outdated
# in range, saving one function call per integer-arithmetic opcode.
@max_int 0x7FFFFFFFFFFFFFFF
@min_int -0x8000000000000000
@deadline_stride State.deadline_stride()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

compile-time dependency, remove

Comment thread lib/lua.ex
Comment on lines +1137 to +1176
@doc """
Sets the instant after which Lua code running on `lua` raises a catchable
`"deadline exceeded"` error, as a `System.monotonic_time(:millisecond)`
value, or `:infinity` for none (the default). `:passed` is what `deadline/1`
returns once Lua has found the deadline passed; it is accepted so a value
read with `deadline/1` can always be set back.

The deadline is checked at loop back-edges and call boundaries, every few
hundred of them, like the `:max_instructions` budget. It is a soft limit:
the clock is read once per stride of those, not on every one, and nothing
bounds how long the work between two of them takes. Elixir functions Lua
calls are not interrupted while they run, and neither are the Lua callbacks
the standard library runs (a `string.gsub` replacement function, a
`table.sort` comparator) nor pattern matching and `string.rep`. A host that
needs a hard limit on untrusted code must run the evaluation in a process it
can kill.

Once Lua finds the deadline passed it stays passed on the state the
evaluation returns, and every later evaluation on that state raises again at
its first loop iteration or call, until the host sets a new deadline. A
`pcall` traps the error, and the protected call's result is returned
normally when nothing that ticks follows it (`return pcall(f)` returns
`false` and the message), but any further loop or call raises again.

It is the deadline a `lua_sethook` count hook gives a host in reference Lua:
a host calling back into Lua from an Elixir function can give that call a
shorter deadline, and restore the previous one with `deadline/1` once it
returns, so only the callback fails.

iex> lua = Lua.new() |> Lua.set_deadline(System.monotonic_time(:millisecond))
iex> {[false, message], _lua} = Lua.eval!(lua, "return pcall(function() while true do end end)")
iex> message =~ "deadline exceeded"
true
"""
@spec set_deadline(t(), integer() | :infinity | :passed) :: t()
def set_deadline(%__MODULE__{state: state} = lua, deadline)
when is_integer(deadline) or deadline in [:infinity, :passed] do
%{lua | state: %{state | deadline: deadline}}
end

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the deadline API is a bit confusing as written. I believe its expecting users to add time to System.monotonic_time(:millisecond).

Instead, I would expect that users would just pass a timeout value, and then we internally use monotonic time to set the deadline.

e.g. instead of

Lua.set_deadline(lua, System.monotonic_time(:millisecond) + 30)

Users would do

Lua.set_deadline(lua, to_timeout(minute: 1))`

it always expects values to be >=0, and measured as a millisecond offset .

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In addition, I find the documentation here to be very confusing and hard to read

deadline/1 returns the milliseconds left. :infinity clears; 0 is passed at once;
negatives and non-integers raise ArgumentError. Docs rewritten.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants